using System.Linq;
using System.Data.Entity;

namespace SkeletonNET.Base.Crud.UnitOfWork
{
    public abstract class EfContextBase : DbContext, IUnitOfWork,
        System.IDisposable, System.Data.Entity.Infrastructure.IObjectContextAdapter
    {
        public EfContextBase(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {

        }

        public EfContextBase()
        {

        }

        public virtual void Commit()
        {
            base.SaveChanges();
        }

        public virtual void Attach<TEntity>(TEntity entity) where TEntity : class
        {
            Set<TEntity>().Attach(entity);
        }

        public virtual TEntity Add<TEntity>(TEntity entity) where TEntity : class
        {
            return Set<TEntity>().Add(entity);
        }

        public virtual IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
        {
            return Set<TEntity>();
        }

        public virtual void Remove<TEntity>(TEntity entity) where TEntity : class
        {
            Set<TEntity>().Remove(entity);
        }

        public TEntity Update<TEntity>(TEntity entity) where TEntity : class
        {
            Entry<TEntity>(entity).State = System.Data.EntityState.Modified;
            return entity;
        }
    }
}